package com.hank.jms.message;

import com.hank.common.Constant;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;
import javax.xml.soap.Text;
import java.util.Enumeration;

public class ReceiverMessage {
    public static String BROKER_URL="tcp://192.168.0.103:61616";
    public static void main(String[] args){
        //创建连接工厂
        ConnectionFactory connectionFactory=new ActiveMQConnectionFactory(Constant.BROKER_URL);
        Connection connection= null;
        try {
            //通过工厂获取一个连接
            connection = connectionFactory.createConnection();
            connection.start();

            //通过连接创建一个会话,并默认设开启事务,自动确认消息
            Session session=connection.createSession(Boolean.FALSE,Session.CLIENT_ACKNOWLEDGE);
            //通过会话构建一个目的地
            Destination destination=session.createQueue("my-test-queue");
            //再通过session创建一个消息发送者，并设定发送目的地对象
            MessageConsumer consumer=session.createConsumer(destination);

            for (int i = 0; i <50 ; i++) {


//                Message msg=consumer.receive();
//                if(msg instanceof MapMessage){
//                    MapMessage message=(MapMessage)msg;//同步消费
//                    System.out.println("Receiver MapMessage >>"+message.getString("text"));
//
//                }else if (msg instanceof TextMessage){
//                    TextMessage message=(TextMessage)msg;//同步消费
//                    System.out.println("Receiver TextMessage >>"+message.getText());
//
//                }

                TextMessage message=(TextMessage)consumer.receive();//同步消费
                System.out.println("Receiver Message >>"+message.getText());


                message.getJMSReplyTo();
                Enumeration propertys=message.getPropertyNames();
                while(propertys.hasMoreElements()){
                    String propertyName=String.valueOf(propertys.nextElement());
                    System.out.println("JMS Property Name:"+propertyName+"="+message.getStringProperty(propertyName));
                }
                String jmsType=message.getJMSType();
                String tm=String.valueOf(message.getJMSTimestamp());
                String jmsPriority=String.valueOf(message.getJMSPriority());
                System.out.println("JMSHead> JMSType:"+jmsType+"/t JMSTimestamp:"+tm+" /t jmsPriority="+jmsPriority);

                if(i==0) {
                    message.acknowledge();
                }
//                session.commit();
//                session.rollback();
            }
            session.close();
            connection.close();

        } catch (JMSException e) {
            e.printStackTrace();
        } finally {
            try{
                if(connection!=null){
                    connection.close();
                    connection=null;
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }


    }
}
